package com.richfit.barcodesystem_cczt.fragments;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.LinearLayout;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.alertview.AlertView;
import com.google.android.material.tabs.TabLayout;
import com.richfit.barcodesystem_cczt.R;
import com.richfit.barcodesystem_cczt.activitis.Main;
import com.richfit.barcodesystem_cczt.activitis.adapters.BottomDialogMenuAdapter;
import com.richfit.barcodesystem_cczt.activitis.model.base.Result;
import com.richfit.barcodesystem_cczt.activitis.model.login.BottomMenuEntity;
import com.richfit.barcodesystem_cczt.activitis.model.main.IncrementalEntity;
import com.richfit.barcodesystem_cczt.databinding.FragmentBatchwarehousingBinding;
import com.richfit.barcodesystem_cczt.fragments.adapters.BatchWareHousing_Detail_Adapter;
import com.richfit.barcodesystem_cczt.fragments.base.BaseFragment;
import com.richfit.barcodesystem_cczt.fragments.model.ZBoxEntity;
import com.richfit.barcodesystem_cczt.network.OkHttpUtils;
import com.richfit.barcodesystem_cczt.utils.Urls;
import com.richfit.barcodesystem_cczt.utils.dialog.DialogHelper;
import com.richfit.barcodesystem_cczt.utils.toast.ToastUtil;
import com.richfit.barcodesystem_cczt.widget.RichAutoEditText;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author cl
 */
public class BatchWarehousing extends BaseFragment {
    private FragmentBatchwarehousingBinding binding;
    private BatchWareHousing_Detail_Adapter adapter;
    private String bizType;
    private ZBoxEntity zBoxEntity;
    private Context context;
    /**
     * 列表数据
     */
    private List<ZBoxEntity.Line> list = new ArrayList<>();

    public BatchWarehousing(String bizType) {
        this.bizType = bizType;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentBatchwarehousingBinding.inflate(inflater, container, false);
        initView();
        initData();
        return binding.getRoot();
    }

    private void initView() {
        context = this.getContext();
        //初始化加载库存地点
        setIncremental(binding.icdHead.SpInv);
        binding.icdHead.EdtZBoxNum.setText("");
        binding.icdHead.TxtSupplierDesc.setText("");
        binding.icdHead.TxtSupplierDesc.setTag(R.id.supplierid, "");
        binding.icdHead.TxtSupplierDesc.setTag(R.id.suppliercode, "");
        binding.icdHead.TxtProjectArea.setText("");
        binding.icdHead.TxtContractNum.setText("");

        binding.icdHead.EdtLocation.setText("");
        binding.icdHead.TxtTransferDate.setText(getTimes(new Date(), "yyyy-MM-dd"));
        binding.icdHead.EdtZBoxNum.setOnClickListener(v -> {
            binding.icdHead.EdtZBoxNum.setText("");
        });
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initData() {
        binding.tabLayoutTitle.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int selectTab = tab.getPosition();
                if (selectTab == -1 || selectTab == 0) {
                    binding.icdHead.getRoot().setVisibility(View.VISIBLE);
                    binding.icdDetail.getRoot().setVisibility(View.GONE);
                } else if (selectTab == 1) {
                    binding.icdHead.getRoot().setVisibility(View.GONE);
                    binding.icdDetail.getRoot().setVisibility(View.VISIBLE);
                    //判断是否选择了库存地点和是否输入了仓位
                    IncrementalEntity incrementalEntity = (IncrementalEntity) binding.icdHead.SpInv.getTag();
                    if (TextUtils.isEmpty(incrementalEntity.getName())) {
                        ToastUtil.showTextLong("请在台头页选择库存地点", binding.getRoot());
                    } else {
                        if (TextUtils.isEmpty(binding.icdHead.EdtLocation.getText().toString().trim())) {
                            ToastUtil.showTextLong("请在台头页输入仓位", binding.getRoot());
                        } else {
                            for (int i = 0; i < list.size(); i++) {
                                list.get(i).setLocation(binding.icdHead.EdtLocation.getText().toString().trim());
                            }
                            adapter.notifyDataSetChanged();
                        }
                    }
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });

        binding.icdHead.EdtZBoxNum.setOnRichAutoEditTouchListener((view, text) -> {
            getRefData(text);
        });
        //0:日期（年月日）；1：时间（小时分钟）；2：日期时间（年月日+小时分钟）
        int dateType = 0;
        binding.icdHead.TxtTransferDate.setOnClickListener(v -> {
            setDate(dateType, binding.icdHead.TxtTransferDate).show();
        });
        binding.icdDetail.floatingButton.setOnClickListener(v -> {
            showChooseDialog();
        });
        setViewMove(binding.icdDetail.floatingButton);

    }

    /**
     * 条码扫描事件
     *
     * @param type
     * @param list
     */
    @Override
    public void handleBarCodeScanResult(String type, String[] list) {
        if (list != null) {
            View vFocus = this.getActivity().getWindow().getDecorView().findFocus();

            if (vFocus instanceof RichAutoEditText) {
//                ((EditText) vFocus).setText("当前焦点");
                RichAutoEditText richAutoEditText = (RichAutoEditText) vFocus;
                if (richAutoEditText.getId() == binding.icdHead.EdtZBoxNum.getId()) {
                    //抬头 装箱单
                    binding.icdHead.EdtZBoxNum.setText(list[0]);
                    getRefData(list[0]);
                    binding.icdHead.EdtZBoxNum.setText("");
                } else if (richAutoEditText.getId() == binding.icdHead.EdtLocation.getId()) {
                    //抬头  仓位
                    binding.icdHead.EdtLocation.setText(list[0]);
                }

            }
            ToastUtil.showTextShort(list[0]);
        }
    }

    private void getRefData(String boxNum) {
        DialogHelper dialogHelper = new DialogHelper(this.getActivity());
        dialogHelper.showLoadingDialog("正在装箱单信息");
        OkHttpUtils okHttpUtils = OkHttpUtils.getInstance();
        okHttpUtils.doGet(Urls.URL_ZBOX + "?zboxNum=" + boxNum + "&bizType=" + bizType, bo.cookie, new OkHttpUtils.NetCallBack() {
            @Override
            public void onSuccess(Result result) {
                dialogHelper.dismissDialog();
                String data = gson.toJson(result.getData());
                zBoxEntity = gson.fromJson(data, ZBoxEntity.class);
                setItemHead(zBoxEntity);
                list = zBoxEntity.getLines();
                setItemDetail();
            }

            @Override
            public void onFailure(Exception e) {
                dialogHelper.dismissDialog();
            }
        });
    }

    void setItemHead(ZBoxEntity zBoxEntity) {
        binding.icdHead.EdtZBoxNum.setText("");
        binding.icdHead.TxtZBoxNum.setText(zBoxEntity.getZboxNum());
        binding.icdHead.TxtSupplierDesc.setText(zBoxEntity.getSupplierDesc());
        binding.icdHead.TxtSupplierDesc.setTag(R.id.supplierid, zBoxEntity.getSupplierId());
        binding.icdHead.TxtSupplierDesc.setTag(R.id.suppliercode, zBoxEntity.getSupplierCode());
        binding.icdHead.TxtProjectArea.setText(zBoxEntity.getProjectArea());
        binding.icdHead.TxtContractNum.setText(zBoxEntity.getContractNum());

        binding.icdHead.EdtLocation.setText("");
        binding.icdHead.TxtTransferDate.setText(getTimes(new Date(), "yyyy-MM-dd"));
        //再次获取焦点
        binding.icdHead.EdtZBoxNum.setFocusable(true);
        binding.icdHead.EdtZBoxNum.setFocusableInTouchMode(true);
        binding.icdHead.EdtZBoxNum.requestFocus();
    }

    void setItemDetail() {
        adapter = new BatchWareHousing_Detail_Adapter(this.getContext(), list);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this.getContext(), 1, RecyclerView.VERTICAL, false);
        binding.icdDetail.baseDetailRecyclerView.setLayoutManager(gridLayoutManager);
//        binding.baseDetailRecyclerView.addItemDecoration(new DividerGridItemDecoration(this.getContext()));
        binding.icdDetail.baseDetailRecyclerView.setAdapter(adapter);
        // 设置数据后就要给RecyclerView设置点击事件,menusBean:九宫格单项的对象
        adapter.setOnItemClickListener((position, line) -> setOnItemClick(position, line));
        adapter.setOnItemRemoveListener((position, line) -> setOnItemRemove(position, line));

    }

    /**
     * 菜单点击事件
     *
     * @param line
     */
    private void setOnItemClick(int position, ZBoxEntity.Line line) {
        list.get(position).setIsChecked(!list.get(position).getIsChecked());
        adapter.notifyDataSetChanged();
    }

    private void setOnItemRemove(int position, ZBoxEntity.Line line) {
        list.remove(position);
        adapter.notifyDataSetChanged();
        ToastUtil.showTextLong("删除了：" + line.getBoxNo(), binding.getRoot());
    }

    private void showChooseDialog() {
        View rootView = LayoutInflater.from(this.getContext()).inflate(R.layout.dialog_bottom_menu, null);
        GridView menu = (GridView) rootView.findViewById(R.id.gd_menus);
        ArrayList<BottomMenuEntity> items = new ArrayList<>();
        BottomMenuEntity item = new BottomMenuEntity();
        item.setMenuName("过账");
        item.setMenuImageRes(R.mipmap.icon_data_submit);
        items.add(item);

        item = new BottomMenuEntity();
        item.setMenuName("全选");
        item.setMenuImageRes(R.mipmap.icon_all_select);
        items.add(item);

        item = new BottomMenuEntity();
        item.setMenuName("反选");
        item.setMenuImageRes(R.mipmap.icon_reverse_select);
        items.add(item);


        BottomDialogMenuAdapter adapter = new BottomDialogMenuAdapter(this.getContext(), items);
        menu.setAdapter(adapter);

        final Dialog dialog = new Dialog(this.getContext(), R.style.MaterialDialogSheet);
        dialog.setContentView(rootView);
        dialog.setCancelable(true);
        dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        dialog.show();

        menu.setOnItemClickListener((adapterView, view, position, id) -> {
            switch (position) {
                case 0:
                    //判断是否选择了库存地点和是否输入了仓位
                    IncrementalEntity incrementalEntity = (IncrementalEntity) binding.icdHead.SpInv.getTag();
                    if (TextUtils.isEmpty(incrementalEntity.getName())) {
                        ToastUtil.showTextLong("请在台头页选择库存地点", binding.getRoot());
                        break;
                    } else {
                        if (TextUtils.isEmpty(binding.icdHead.EdtLocation.getText().toString().trim())) {
                            ToastUtil.showTextLong("请在台头页输入仓位", binding.getRoot());
                            break;
                        }

                    }
                    List<ZBoxEntity.CommitLine> commit_lines = new ArrayList<>();

                    for (ZBoxEntity.Line line : list) {
                        if (line.getIsChecked()) {
                            ZBoxEntity.CommitLine commitLine = new ZBoxEntity.CommitLine();
                            commitLine.setZboxLineId(line.getId());
                            commit_lines.add(commitLine);
                        }
                    }
                    ZBoxEntity.Commit commit = new ZBoxEntity.Commit();
                    commit.setZboxId(zBoxEntity.getId());
                    commit.setCommitType("SUBMIT");
                    commit.setBizType("IN_DAI_FA_YUN");
                    commit.setWhId(((IncrementalEntity) binding.icdHead.SpInv.getTag()).getId());
                    commit.setLocation(binding.icdHead.EdtLocation.getText().toString().trim());
                    commit.setRefLines(commit_lines);
                    new AlertView("提示", "确定提交选中的箱号", null,
                            new String[]{"确定", "取消"}, null, this.getActivity(),
                            AlertView.Style.Alert, (o, position1) -> {
                        if (position1 == 0) {
                            Log.i("TAG", "showChooseDialog: " + gson.toJson(commit));
                            BatchIn(gson.toJson(commit));
                        }
                    }).show();
                    break;
                case 1:
                    //全选
                    for (int i = 0; i < list.size(); i++) {
                        list.get(i).setIsChecked(true);
                    }
                    setItemDetail();
                    break;
                case 2:
                    //反选
                    for (int i = 0; i < list.size(); i++) {
                        list.get(i).setIsChecked(!list.get(i).getIsChecked());
                    }
                    setItemDetail();
                    break;

                default:
                    break;
            }
            dialog.dismiss();
        });
    }

    /**
     * 批量入库
     */
    private void BatchIn(String commit_json) {
        DialogHelper dialogHelper = new DialogHelper(this.getActivity());
        dialogHelper.showLoadingDialog("正在提交入库信息！");
        OkHttpUtils okHttpUtils = OkHttpUtils.getInstance();
//        bo.maps = Urls.getDefaultConfigrationMap();
//        bo.maps.put("commitType", "SUBMIT");
//        bo.maps.put("bizType", "IN_DAI_FA_YUN");
//        //装箱单ID
//        bo.maps.put("zboxId", zboxid);
//        //仓库ID
//        bo.maps.put("whId", whId);
//        //仓库位置
//        bo.maps.put("location", location);
//        //箱子ID
//        bo.maps.put("refLines", zboxLineIds);
        okHttpUtils.doPostJson(Urls.URL_ZBOX_BATCH_IN, bo.cookie, commit_json, new OkHttpUtils.NetCallBack() {
            @Override
            public void onSuccess(Result result) {
                dialogHelper.dismissDialog();
//                String data = gson.toJson(result.getData());
                ToastUtil.showTextShort("过账成功！", binding.getRoot());
                Main main = (Main) getActivity();
                main.setFragments(bizType);
            }

            @Override
            public void onFailure(Exception e) {
                dialogHelper.dismissDialog();
            }
        });
    }


}
